<template>
  <div>
    <van-button type="primary" @click="$router.push('/register')">前往注册</van-button>
    <van-form @submit="onSubmit">
      <van-field
        v-model="user.userName"
        name="username"
        label="用户名"
        placeholder="用户名"
        :rules="[
          { required: true, message: '请填写用户名' }
        ]"
      />
      <van-field
        v-model="user.pwd"
        type="password"
        name="pwd"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">提交</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { doLogin } from '@api'
import { Toast } from 'vant'
export default {
  data () {
    return {
      user: {
        userName: '',
        pwd: ''
      }
    }
  },
  methods: {
    onSubmit (params) {
      // 提交表单的事件
      doLogin({
        ...params,
        deviceId: '23',
        deviceName: '手机'
      }).then(res => {
        if (res.data.code === 0) {
          // 登录成功
          localStorage.setItem('token', res.data.data.token)
          Toast({
            type: 'success',
            message: '登录成功',
            duration: 1000,
            onClose: () => {
              // 重定向到其他页面 （到首页，到跳过过来页面）
              if (this.$route.query.from) {
                this.$router.replace(this.$route.query.from)
              } else {
                this.$router.replace('/home')
              }
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
